
<div class="mt-9 max-w-md">

    <div class="grid grid-cols-1 gap-6">
      {#if  wallet!=""}
       <span>钱包地址： {wallet}</span>
       {:else}
       <MButton on:click={connect} title="连接钱包"/>
      {/if}
      <h1>发起【提币提议】</h1>
      <MTextInput  bind:value={pTitle}   placeholder="提议标题"/>
      <MTextArea  bind:value={pContent}   placeholder="提议详情"/>
      <MTextInput  bind:value={pToken}   placeholder="代币合约地址"/>
      <MTextInput  bind:value={pAddress}   placeholder="接收代币的地址"/>
      <MTextInput  bind:value={pAmount}   placeholder="数量"/>

      <MButton on:click={confirm} title="发起"/>
    </div>
    </div>



    <script lang="ts">
    import {abi} from '../../constants'
    import MButton from '../../components/MButton.svelte'
    import MTextInput from '../../components/MTextInput.svelte'
import MTextArea from '../../components/MTextArea.svelte';

    let wallet = ""
    let contract = ""
    export let address = ""

    let pTitle=""
    let pContent = ""
    let pToken = "0x9e01544f47879e51bb4df1b5e1e5a55b73f90bcd"
    let pAddress = ""
    let pAmount = ""
    const connect = ()=>{
    if (window.ethereum) {
      window.ethereum
        .request({ method: "eth_requestAccounts" })
        .then((accounts)=>{
          if (accounts.length === 0) { Swal.fire('未检测到 Web3 环境，如你已经安装请启用并刷新页面!')} else {
            wallet=accounts[0]
            let web3 = new Web3(window.ethereum);
            contract = new web3.eth.Contract(abi,address,{
            from:wallet
            })
        }
        }).catch((err) => {
        Swal.fire('未检测到 Web3 环境，如你已经安装请启用并刷新页面!')
        console.error(err);
        })
    } else { Swal.fire('未检测到 Web3 环境，如你已经安装请启用并刷新页面!')  }
   }

   const confirm = async ()=>{
    if(!contract){
        Swal.fire('未连接钱包')
        return
    }
    if(pTitle==""||pContent==""||pToken==""||pAddress==""||pAmount==""){
        Swal.fire('请检查表单是否填写完整！')
        return
    }
    try{
        Swal.fire('正在创建，请耐心等待...')
        const res = await contract.methods.createWithDrawProposal(pTitle,pContent,pToken,pAddress,pAmount).send({});
        const id = parseInt(res["events"]['ProposalCreated']['raw']['data'], 16); 
        Swal.fire(`创建成功，您的提议编号是 ${id}`)

        console.log({res})
    }catch(e){
      console.error(e)
      Swal.fire(`出现错误: ${JSON.stringify(e)}`)
    }
   }

   
 </script>